package com.example.demo1;

import com.example.demo1.common.ApiResponse;
import com.example.demo1.Book;
import com.example.demo1.BookService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/books")
public class BookController {

    private final BookService bookService;

    public BookController(BookService bookService) {
        this.bookService = bookService;
    }

    // 获取所有图书（支持分页、搜索、状态筛选）
    @GetMapping
    public ApiResponse<Page<Book>> getAllBooks(
            @RequestParam(required = false) String title,
            @RequestParam(required = false) Boolean available,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size
    ) {
        Pageable pageable = PageRequest.of(page, size);
        Page<Book> books = bookService.searchBooks(title, available, pageable);
        return ApiResponse.success(books);
    }

    // 根据 ID 获取图书
    @GetMapping("/{id}")
    public ApiResponse<Book> getBookById(@PathVariable Long id) {
        Book book = bookService.getBookById(id);
        return ApiResponse.success(book);
    }

    // 添加图书
    @PostMapping
    public ApiResponse<Book> addBook(@RequestBody Book book) {
        Book savedBook = bookService.addBook(book);
        return ApiResponse.success(savedBook);
    }

    // 更新图书
    @PutMapping("/{id}")
    public ApiResponse<Book> updateBook(@PathVariable Long id, @RequestBody Book book) {
        Book updatedBook = bookService.updateBook(id, book);
        return ApiResponse.success(updatedBook);
    }

    // 删除图书
    @DeleteMapping("/{id}")
    public ApiResponse<Void> deleteBook(@PathVariable Long id) {
        bookService.deleteBook(id);
        return ApiResponse.success();
    }

    // 借阅图书
    @PostMapping("/{id}/borrow")
    public ApiResponse<Void> borrowBook(@PathVariable Long id) {
        bookService.borrowBook(id);
        return ApiResponse.success();
    }

    // 归还图书
    @PostMapping("/{id}/return")
    public ApiResponse<Void> returnBook(@PathVariable Long id) {
        bookService.returnBook(id);
        return ApiResponse.success();
    }
}